package com.codewsq.java1;

import com.codewsq.entity.Person;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorTest {

    /*
     * 获取运行时类的构造器
     * */
    @Test
    public void test() {
        Class<Person> clazz = Person.class;

        /*
         * getConstructors()：获取当前类中声明的public构造器
         * */
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        System.out.println("----------------------------------------------");
        /*
         * getDeclaredConstructors():获取当前运行时类中声明的所有构造器
         * */
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
    }

    /*
     * 如何调用运行时类中的指定的构造器
     */
    @Test
    public void test1() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<Person> clazz = Person.class;

        // 调用构造函数：private Person(String name)
        /*
        1.getDeclaredConstructor(Class<?>... parameterTypes)： 获取指定的构造器
           parameterTypes参数：指明构造器的参数类型列表
         */
        Constructor<?> constructor = clazz.getDeclaredConstructor(String.class);

        // 2. 保证构造器可访问
        constructor.setAccessible(true);

        // 3.调用构造器创建运行时类的对象
//        Object o = constructor.newInstance("张三");
        Person person = (Person) constructor.newInstance("张三");
        System.out.println(person);


    }
}
